/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package utils

import (
	"did-service/common/crypto/gm"
	"did-service/common/logger"
	"encoding/json"
	"io/ioutil"
	"math/rand"
	"path/filepath"
	"reflect"
	"strconv"
	"strings"

	"github.com/mitchellh/mapstructure"
)

var log = logger.GetLogger("common.util")

// 首字母大写
func FirstUpper(org string) string {
	return strings.ToUpper(org[:1]) + org[1:]
}
func StrToLower(str string) string {
	return strings.ToLower(str)
}

// yaml to 字节数组
func Yamls2Bytes(rootPath string, files []string) [][]byte {
	yamls := make([][]byte, len(files))
	for i, name := range files {
		yamlBytes, err := ioutil.ReadFile(filepath.Join(rootPath, name))
		if err != nil {
			panic(err)
		}
		yamls[i] = yamlBytes

	}
	return yamls
}

func Bytes2Int(bts []byte) int {
	sData := string(bts)
	iData, err := strconv.Atoi(sData)
	if err != nil {
		return 0
	}
	return iData
}
func StrJoin(strs ...string) string {
	var builder strings.Builder
	for _, str1 := range strs {
		builder.WriteString(str1)
	}
	return builder.String()
}

// 生成随机字符串
func GetRandomString(length int) string {
	str := "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	return random(length, str)
}

// 生成随机字符串
func GetRandomLowerString(length int) string {
	str := "0123456789abcdefghijkmnopqrstuvwxyz"
	return random(length, str)
}
func random(length int, baseStr string) string {
	if length <= 0 {
		return ""
	}
	b := make([]byte, length)
	arc := uint8(0)
	if _, err := rand.Read(b[:]); err != nil {
		return ""
	}
	for i, x := range b {
		arc = x & 31
		b[i] = baseStr[arc]
	}
	return string(b)
}

func Map2Struct(data map[string]interface{}, toData interface{}) {
	_ = mapstructure.Decode(data, &toData)
}

func RandomGenerateIdByTime(flag string) string {
	return "ibes-" + flag + "-" + GetRandomString(20)
}
func RandomIdByTime(prefix string, length int) string {
	return prefix + GetRandomString(length)
}

func StructToMap(obj interface{}) map[string]interface{} {
	types := reflect.TypeOf(obj)
	values := reflect.ValueOf(obj)

	var data = make(map[string]interface{})
	for i := 0; i < types.NumField(); i++ {
		value := values.Field(i).Interface()
		if value != nil && value != "" {
			data[types.Field(i).Name] = value
		}
	}
	return data
}

func ArrayContains(arrays []string, item string) bool {
	for _, str := range arrays {
		if str == item {
			return true
		}
	}
	return false
}

func RandomInt(min, max int64) int64 {
	if min >= max || min == 0 || max == 0 {
		return max
	}
	return rand.Int63n(max-min) + min
}

// "["","",...]" to ["","",...]
func StrToJsonArray(str string) []string {
	var arr []string
	err := json.Unmarshal([]byte(str), &arr)
	if err != nil {
		log.Errorf("StrToJsonArray error: %s", err.Error())
	}
	return arr
}

// ["","",...] to "["","",...]"
func JsonArrayToStr(arr []string) string {
	bts, _ := json.Marshal(arr)
	return string(bts)
}

func ArrayToString(arr []string) string {
	var result string
	for _, i := range arr { //遍历数组中所有元素追加成string
		result += i
	}
	return result
}

func HashArrayToHash(arr []string) string {
	sumStr := StrJoin(arr...)
	hash := gm.Sm3(sumStr)
	return hash
}
